package com.away.sequence;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.security.auth.Subject;
import java.util.List;

@RestController
@SpringBootApplication
@RequestMapping("/sequenceProducerController")
public class SequenceProducerController {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    @GetMapping("sendMsg2MQ")
    public String sendMsg2MQ() throws InterruptedException, RemotingException, MQClientException, MQBrokerException {

        Long id = System.currentTimeMillis();
        OrderEntity insertOrder = new OrderEntity("insert",id);
        OrderEntity updateOrder = new OrderEntity("update",id);
        OrderEntity deleteOrder = new OrderEntity("delete",id);

        Message inserMsg = new Message("test_topic",insertOrder.toString().getBytes());
        Message updateMsg = new Message("test_topic",updateOrder.toString().getBytes());
        Message deleteMsg = new Message("test_topic",deleteOrder.toString().getBytes());

        DefaultMQProducer producer = rocketMQTemplate.getProducer();
        producer.send(inserMsg, new MessageQueueSelector() {
            @Override
            public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {

                return mqs.get(id.intValue()%mqs.size());
            }
        }, id);
//        producer.send(inserMsg);
//        producer.send(updateMsg);
//        producer.send(deleteMsg);

        return "SUCCESS";
    }
    public static void main(String[] args) {
        SpringApplication.run(SequenceProducerController.class);
    }
}
